package com.bestcem.xm.openplatform.grpc.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bestcem.xm.openplatform.convert.grpc.OpenplatformGrpcConvertMapper;
import com.bestcem.xm.openplatform.entity.*;
import com.bestcem.xm.openplatform.grpc.v1.services.*;
import com.bestcem.xm.openplatform.mapper.*;
import io.grpc.stub.StreamObserver;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.apache.commons.collections4.CollectionUtils;
import zhongyan.xm.base.v1.Base;

import java.util.ArrayList;
import java.util.List;


@GrpcService
@Slf4j
@RequiredArgsConstructor
public class BaseOpenplatformGrpcService extends BaseOpenplatformServiceGrpc.BaseOpenplatformServiceImplBase {

    private static final Base.Status SUCCESS_STATUS = Base.Status.newBuilder().setCode(Base.Code.OK).build();
    private static final Base.Status FAIL_STATUS = Base.Status.newBuilder().setCode(Base.Code.ERROR).build();

    private @NonNull OpenplatformExtparamMapper extparamMapper;
    private @NonNull OpenplatformGrpcConvertMapper openplatformGrpcConvertMapper;
    private @NonNull OpenplatformExtparamenummanageMapper extparamenummanageMapper;
    private @NonNull OpenplatformFunctionoptionMapper functionoptionMapper;
    private @NonNull OpenplatformEncryptionconfigMapper encryptionconfigMapper;
    private @NonNull OpenplatformConditionmanageMapper conditionmanageMapper;
    private @NonNull OpenplatformSystemmanageMapper systemmanageMapper;
    private @NonNull OpenplatformOpencustomdeliverMapper opencustomdeliverMapper;

    @Override
    public void getExtParam(GetExtParamRequest request, StreamObserver<ExtParamResponse> responseObserver) {
        ExtParamResponse.Builder builder = ExtParamResponse.newBuilder();
        OpenplatformExtparam openplatformExtparam = extparamMapper.selectById(request.getId());
        if (openplatformExtparam == null) {
            builder.setStatus(Base.Status.newBuilder().setCode(Base.Code.ERROR).setMessage("getExtParam not found").build());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        ExtParam extParam = openplatformGrpcConvertMapper.toGrpcExtParam(openplatformExtparam);
        builder.setExtParam(extParam);
        builder.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listExtParamEnumManage(ListExtParamEnumManageRequest request, StreamObserver<ExtParamEnumManageSearchResponse> responseObserver) {
        ExtParamEnumManageSearchResponse.Builder builder = ExtParamEnumManageSearchResponse.newBuilder();
        ExtParamEnumManage extParamEnumManage = request.getExtParamEnumManage();
        LambdaQueryWrapper<OpenplatformExtparamenummanage> queryWrapper = new LambdaQueryWrapper<>();

        if (ObjectUtil.isNotEmpty(extParamEnumManage)) {
            if (ObjectUtil.isNotEmpty(extParamEnumManage.getOrgId())) {
                queryWrapper.eq(OpenplatformExtparamenummanage::getOrgId, extParamEnumManage.getOrgId());
            }
            if (ObjectUtil.isNotEmpty(extParamEnumManage.getExtParamId())) {
                queryWrapper.eq(OpenplatformExtparamenummanage::getExtParamId, extParamEnumManage.getExtParamId());
            }
        }
        if (ObjectUtil.isNotEmpty(request.getStatusList())) {
            queryWrapper.in(OpenplatformExtparamenummanage::getStatus, request.getStatusList());
        }

        List<OpenplatformExtparamenummanage> extparamenummanageList = extparamenummanageMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(extparamenummanageList)) {
            builder.addAllExtParamEnumManageList(new ArrayList<>());
            builder.setStatus(SUCCESS_STATUS);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        builder.addAllExtParamEnumManageList(openplatformGrpcConvertMapper.toGrpcExtParamEnumManageList(extparamenummanageList));
        builder.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listEncryptionConfig(ListEncryptionConfigRequest request, StreamObserver<EncryptionConfigSearchResponse> responseObserver) {
        EncryptionConfigSearchResponse.Builder builder = EncryptionConfigSearchResponse.newBuilder();
        EncryptionConfig encryptionConfig = request.getEncryptionConfig();
        LambdaQueryWrapper<OpenplatformEncryptionconfig> queryWrapper = new LambdaQueryWrapper<>();

        if (ObjectUtil.isNotEmpty(encryptionConfig)) {
            if (ObjectUtil.isNotEmpty(encryptionConfig.getOrgId())) {
                queryWrapper.eq(OpenplatformEncryptionconfig::getOrgId, encryptionConfig.getOrgId());
            }
        }

        List<OpenplatformEncryptionconfig> encryptionconfigList = encryptionconfigMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(encryptionconfigList)) {
            builder.addAllEncryptionConfigList(new ArrayList<>());
            builder.setStatus(SUCCESS_STATUS);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        builder.addAllEncryptionConfigList(openplatformGrpcConvertMapper.toGrpcEncryptionConfigList(encryptionconfigList));
        builder.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void getFunctionOption(GetFunctionOptionRequest request, StreamObserver<FunctionOptionResponse> responseObserver) {
        FunctionOptionResponse.Builder builder = FunctionOptionResponse.newBuilder();
        OpenplatformFunctionoption functionoption = functionoptionMapper.selectById(request.getId());
        if (functionoption == null) {
            builder.setStatus(Base.Status.newBuilder().setCode(Base.Code.ERROR).setMessage("getFunctionOption not found").build());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        FunctionOption option = openplatformGrpcConvertMapper.toGrpcFunctionOption(functionoption);
        builder.setFunctionOption(option);
        builder.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listExtParam(ListExtParamRequest request, StreamObserver<ExtParamSearchResponse> responseObserver) {
        ExtParamSearchResponse.Builder builder = ExtParamSearchResponse.newBuilder();
        String search = request.getSearch();
        ExtParam extParam = request.getExtParam();
        LambdaQueryWrapper<OpenplatformExtparam> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(extParam)) {
            if (ObjectUtil.isNotEmpty(extParam.getOrgId())) {
                queryWrapper.eq(OpenplatformExtparam::getOrgId, extParam.getOrgId());
            }
            if (ObjectUtil.isNotEmpty(extParam.getName())) {
                queryWrapper.eq(OpenplatformExtparam::getName, extParam.getName());
            }
            //注意，这里没传会默认给0，查看所有调用的方法，没找到有传0的情况，先临时处理
            if (extParam.getDtypeValue() > 0) {
                queryWrapper.eq(OpenplatformExtparam::getDtype, extParam.getDtype().getNumber());
            }
        }
        if (ObjectUtil.isNotEmpty(request.getStatusList())) {
            queryWrapper.in(OpenplatformExtparam::getStatus, request.getStatusList());
        }
        List<OpenplatformExtparam> extparamList = extparamMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(extparamList)) {
            builder.addAllExtParamList(new ArrayList<>());
            builder.setStatus(SUCCESS_STATUS);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        builder.addAllExtParamList(openplatformGrpcConvertMapper.toGrpcExtParamList(extparamList));
        builder.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listConditionManage(ListConditionManageRequest request, StreamObserver<ConditionManageSearchResponse> responseObserver) {
        ConditionManageSearchResponse.Builder builder = ConditionManageSearchResponse.newBuilder();
        ConditionManage conditionManage = request.getConditionManage();
//        LambdaQueryWrapper<OpenplatformConditionmanage> queryWrapper = new LambdaQueryWrapper<>(openplatformGrpcConvertMapper.toConditionmanage(conditionManage));
//        List<OpenplatformConditionmanage> conditionmanageList = conditionmanageMapper.selectList(queryWrapper);
        List<OpenplatformConditionmanage> conditionmanageList = conditionmanageMapper.selectList(new LambdaQueryWrapper<OpenplatformConditionmanage>()
                .eq(OpenplatformConditionmanage::getCode, conditionManage.getCode()));
        if (ObjectUtil.isEmpty(conditionmanageList)) {
            builder.addAllConditionManageList(new ArrayList<>());
            builder.setStatus(SUCCESS_STATUS);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        builder.addAllConditionManageList(openplatformGrpcConvertMapper.toGrpcConditionManageList(conditionmanageList));
        builder.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listSystemManage(ListSystemManageRequest request, StreamObserver<SystemManageSearchResponse> responseObserver) {
        SystemManageSearchResponse.Builder builder = SystemManageSearchResponse.newBuilder();
        SystemManage systemmanage = request.getSystemManage();
//        LambdaQueryWrapper<OpenplatformSystemmanage> queryWrapper = new LambdaQueryWrapper<>(openplatformGrpcConvertMapper.toSystemmanage(systemmanage));
//        List<OpenplatformSystemmanage> systemmanageList = systemmanageMapper.selectList(queryWrapper);
        List<OpenplatformSystemmanage> systemmanageList = systemmanageMapper.selectList(new LambdaQueryWrapper<OpenplatformSystemmanage>()
                .eq(OpenplatformSystemmanage::getCode, systemmanage.getCode()));
        if (ObjectUtil.isEmpty(systemmanageList)) {
            builder.addAllSystemManageList(new ArrayList<>());
            builder.setStatus(SUCCESS_STATUS);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        builder.addAllSystemManageList(openplatformGrpcConvertMapper.toGrpcSystemmanageList(systemmanageList));
        builder.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void deleteOpenCustomDeliverByDeliverId(DeleteOpenCustomDeliverByDeliverIdRequest request, StreamObserver<DeleteResponse> responseObserver) {
        DeleteResponse.Builder builder = DeleteResponse.newBuilder();
        String orgId = request.getOrgId();
        List<String> deliverIds = request.getDeliverIdsList();
        log.info("Now to deleteOpenCustomDeliverByDeliverId, orgId = {}, deliverIds = {}", orgId, deliverIds);
        if (CollectionUtils.isEmpty(deliverIds)) {
            builder.setStatus(Base.Status.newBuilder().setCode(Base.Code.ERROR).setMessage("deliverIds is Empty").build());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        LambdaQueryWrapper<OpenplatformOpencustomdeliver> queryWrapper = new
                LambdaQueryWrapper<OpenplatformOpencustomdeliver>().eq(OpenplatformOpencustomdeliver::getOrgId, orgId)
                .in(OpenplatformOpencustomdeliver::getDeliverId, deliverIds);
        int delete = opencustomdeliverMapper.delete(queryWrapper);
        builder.setCount(delete);
        builder.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}
